package com.eyas.business.service.classinfo;

import com.eyas.business.config.webmvc.exception.custom.uncheck.EyasBusinessException;
import com.eyas.business.model.filepath.FileTmpPath;
import com.eyas.business.model.jdbcEntity.table.ClassInfo;
import com.eyas.business.model.pojo.classinfo.ClassInfoSaveDTO;
import com.eyas.core.file.utils.FileUtils;
import com.eyas.core.model.page.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static com.eyas.core.jdbc.utils.CommonJdbcUtils.commonJdbcUtils;

/**
 * @Auther: 王龙龙
 * @Date: 2019/3/5 17:37
 * @Description:
 */
@Service
@Transactional
public class ClassInfoServiceImpl implements ClassInfoService {
    private final static Logger logger = LoggerFactory.getLogger(ClassInfoServiceImpl.class);
    @Override
    public PageResult<ClassInfo> queryClassInfo(String classname, String validflag, int page, int limit) {
        StringBuffer sb = new StringBuffer("");
        List args = new ArrayList();
        sb.append(" select a.classid,a.classname,a.details,a.hours,a.validflag ")
                .append(" from classinfo a ")
                .append(" where 1=1 ");
        if(StringUtils.hasText(classname)) {
            sb.append(" and a.classname like ? ");
            args.add("%"+classname+"%");
        }
        if(StringUtils.hasText(validflag)) {
            sb.append(" and a.validflag=? ");
            args.add(validflag);
        }
        PageResult<ClassInfo> result = commonJdbcUtils.queryForPage(sb.toString(),ClassInfo.class,page,limit,args);
        return result;
    }

    @Override
    public void changeValidflag(int classid) {
       commonJdbcUtils.update("update classinfo set validflag=(case validflag when '1' then '0' else '1' end) where classid=?",classid);
    }

    @Override
    public ClassInfo getClassInfoByClassID(int classid) {
        return commonJdbcUtils.queryObject("select classid,classname,details,ifnull(imgcode,'/upload/image/defaultimg.jpg') as imgcode,validflag,hours " +
                " from classinfo where classid=?",ClassInfo.class,classid);
    }

    @Override
    public void getImgcode(Integer classid, ServletOutputStream outputStream) {
        /*ClassInfo classInfo = commonJdbcUtils.queryObject("select imgcode from classinfo where classid=?",ClassInfo.class,classid);
        if(classInfo.getImgcode()!=null&&classInfo.getImgcode().length>0) {
            try {
                outputStream.write(classInfo.getImgcode());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }


    @Autowired
    private FileTmpPath fileTmpPath;
    @Override
    public void saveClassInfo(ClassInfoSaveDTO dto) {
        //获取文件字节数组对象
        String tmpPath = dto.getNewimgurl();
        String imaurl = null;

        /**
         * 文件操作，文件需要写入到classpath:static/upload/image下，同时，这个文件需要保存到备份文件夹下
         */
        if(StringUtils.hasText(tmpPath)) {
            File file = new File(tmpPath);
            if(!file.exists())
                throw new EyasBusinessException("图片保存失败，请刷新页面重试");
            String backupPath = fileTmpPath.getBcimgpath();
            String serverPath = ClassInfo.class.getResource("/").getPath()+"/static/upload/image/"+file.getName();
            imaurl = "/upload/image/"+file.getName();
            try {
                FileUtils.copyFile(file,backupPath);
                FileUtils.copyFile(file,serverPath);
            } catch (IOException e) {
                e.printStackTrace();
                throw new EyasBusinessException("图片保存失败，请刷新页面重试");
            }finally {
                boolean delsuccess = file.delete();
                if(!delsuccess) {
                    logger.warn("课程配图临时文件删除失败，文件路径:["+file.getAbsolutePath()+"]");
                }
            }

        }

        //保存数据库
        ClassInfo classInfo = null;
        if(dto.getClassid()!=null&&dto.getClassid()>0) {//update
            classInfo = commonJdbcUtils.queryObject("select * from classinfo where classid=?",ClassInfo.class,dto.getClassid());
            dto.setHours(dto.getHours()==null?0:dto.getHours());
            BeanUtils.copyProperties(dto,classInfo,"classid","validflag","imgcode");
            if(StringUtils.hasText(tmpPath))
                classInfo.setImgcode(imaurl);
            commonJdbcUtils.update(classInfo);
        }else {//insert
            classInfo = new ClassInfo();
            classInfo.setClassname(dto.getClassname());
            classInfo.setDetails(dto.getDetails());
            classInfo.setHours(dto.getHours()==null?0:dto.getHours());
            classInfo.setValidflag("1");
            classInfo.setImgcode(imaurl);
            commonJdbcUtils.insert(classInfo);
        }


        //删除tmppath下的文件
        /*if(imgbytes!=null&&imgbytes.length>0) {
            File file = new File(tmpPath);
            boolean delsuccess = file.delete();
            if(!delsuccess) {
                logger.warn("课程配图临时文件删除失败，文件路径:["+file.getAbsolutePath()+"]");
            }
        }*/
    }

    @Override
    public List<ClassInfo> queryClassInfoList(Integer userid) {
        if(userid!=null) {
            int count = commonJdbcUtils.queryObject("select count(1) from userandclass where userid=? and validflag='1'",Integer.class,userid);
            if(count>0) {
                return commonJdbcUtils.queryList("select a.classid,a.classname,a.details, ifnull(a.imgcode,'/upload/image/defaultimg.jpg') as imgcode,a.validflag,a.hours " +
                        " from classinfo a,userandclass b where a.validflag='1' and a.classid=b.classid and b.userid=? and b.validflag='1' ",ClassInfo.class,userid);
            }else {
                return new ArrayList<>();
            }
        }
        return commonJdbcUtils.queryList("select classid,classname,details, ifnull(imgcode,'/upload/image/defaultimg.jpg') as imgcode,validflag,hours  from classinfo where validflag='1' ",ClassInfo.class);
    }

    @Override
    public PageResult<ClassInfo> listAllClass(Integer userid) {
        PageResult<ClassInfo> pageResult = new PageResult<>();
        List<ClassInfo> classInfos = commonJdbcUtils.queryList("select a.classid,a.classname,b.validflag from classinfo a left outer join userandclass b " +
                " on a.classid=b.classid and b.userid=? where a.validflag='1' ",ClassInfo.class,userid);
        if(classInfos!=null) {
            pageResult.setCount(classInfos.size());
            pageResult.setData(classInfos);
        }
        pageResult.setMsg("query success");
        return pageResult;
    }
}
